import DateUtils from "../btoolkit/DateUtils";
import BButton from "../btoolkit/components/BButton";
import AudioManager, { AudioOverrideMethod } from "../btoolkit/AudioManager";
import PopupQuestion from "./PopupQuestion";
import App from "../btoolkit/framework/App";
import ChildLockMenu from "./ChildLockMenu";

const { ccclass, property } = cc._decorator;

const KEY_SLEEP_TIME = "SleepTime";

@ccclass
export default class PanelChildLock extends cc.Component {

    static instance: PanelChildLock = null;
    static playRoundsAlready: number = 0;
    static SleepSeconds = 5 * 60;//休息时间（秒）

    /**
     * 每局结束调用
     */
    static onRoundFinish() {
        console.log('回合+1')
        PanelChildLock.playRoundsAlready += 1;
    }

    /**
     * 检查此刻是否需要显示休息界面，需要则自动创建后返回true，否则不创建返回false
     */
    static checkAndLock(): boolean {
        if (PanelChildLock.instance) {
            return true;
        }
        //上次锁定的时间没过，则继续锁定
        if (PanelChildLock.isInLockTime()) {
            PanelChildLock.show();
            return true;
        } else if (PanelChildLock.isOverMaxRound()) {
            //否则，局数超过了最大限制也锁定
            localStorage.setItem(KEY_SLEEP_TIME, new Date().getTime() + '');
            PanelChildLock.show();
            return true;
        }
        return false;
    }

    private static show() {
        if (PanelChildLock.instance) {
            return;
        }
        AudioManager.playFX('common/voice_IAmGoingToSleep');
        if (!PanelChildLock.instance) {
            PanelChildLock.instance = cc.instantiate(App.instance.panelChildLock).getComponent(PanelChildLock);
            PanelChildLock.instance.node.setParent(App.instance.node);
            console.log('完成创建PanelChildLock')
        }
    }

    private static destroy() {
        if (PanelChildLock.instance) {
            console.log('删除休息')
            PanelChildLock.instance.node.destroy();
            PanelChildLock.instance = null;
            //删除时，重新播放开始界面的背景音乐和标题声音
            AudioManager.playBGM('bgm_start', AudioOverrideMethod.SameNameReturn);
            AudioManager.playVoice('voice_GameName', AudioOverrideMethod.SameNameReturn);
        }
    }

    private static isInLockTime() {
        if (PanelChildLock.getSubMS() < PanelChildLock.SleepSeconds * 1000) {
            return true;
        }
        return false;
    }

    private static getSubMS() {
        let saveSleepTimeStr = localStorage.getItem(KEY_SLEEP_TIME);
        if (saveSleepTimeStr) {
            let saveSleepTime = Number(saveSleepTimeStr);
            return new Date().getTime() - saveSleepTime;
        }
        return new Date().getTime();
    }

    private static isOverMaxRound() {
        if (ChildLockMenu.MaxPlayRounds > 0) {
            if (PanelChildLock.playRoundsAlready >= ChildLockMenu.MaxPlayRounds) {
                return true;
            }
        }
        return false;
    }

    onLoad() {
        cc.audioEngine.stopMusic();

        //设置点击冒泡拦截
        this.node.on(cc.Node.EventType.TOUCH_START, (e) => { e.stopPropagation(); });
        //判断时间到自销毁
        if (PanelChildLock.isInLockTime()) {
            this.startTimer(PanelChildLock.SleepSeconds - Math.round(PanelChildLock.getSubMS() / 1000));
        } else if (PanelChildLock.isOverMaxRound()) {
            this.startTimer(PanelChildLock.SleepSeconds);
        }

        //解锁按钮
        BButton.addButton(this.node.getChildByName('BtnUnlock')).setTouchUpEvent(() => {
            PopupQuestion.show(this.onCorrectAnswer, this);
        });
    }

    private onCorrectAnswer(b: boolean) {
        console.log('回答正确吗？' + b);
        if (b) {
            this.onUnlockSuccess();
        }
    }

    private startTimer(seconds: number) {
        //时钟
        let clockLabel = this.node.getChildByName('Clock').getChildByName('ClockLabel').getComponent(cc.Label);
        this.unscheduleAllCallbacks();
        let totalSeconds = seconds;
        this.schedule(() => {
            if (totalSeconds >= 0) {
                this.setTime(clockLabel, totalSeconds);
                totalSeconds -= 1;
                if (totalSeconds < 0) {
                    PanelChildLock.playRoundsAlready = 0;
                    PanelChildLock.destroy();
                }
            }
        }, 1, seconds, 0);
    }

    private setTime(label: cc.Label, seconds: number) {
        let date: Date = new Date();
        //转亚洲时间减去8个小时
        let time = seconds * 1000 - 8 * 60 * 60 * 1000;
        date.setTime(time);
        label.string = '' + DateUtils.dateFormat(date, 'HH:mm:ss');
    }

    private onUnlockSuccess() {
        localStorage.setItem(KEY_SLEEP_TIME, '0');
        PanelChildLock.playRoundsAlready = 0;
        PanelChildLock.destroy();
    }

}
